<template>
  <div class="container-scroll-bar">
    <div class="unit-form-container" :class="layoutType + '-layout'">
      <el-form
        class="full-height-width unit-form"
        :label-position="labelPosition"
        :class="[customClass]"
        :size="size"
        :validate-on-rule-change="false"
      >
        <div v-if="designer.fieldTree.length === 0" class="no-unit-hint">
          请从左侧列表中选择一个组件, 然后用鼠标拖动组件放置于此处.
        </div>
        <div class="form-scrollbar" :style="{ height: scrollerHeight }">
          <el-row :gutter="formConfig.gridGutter" @click="clearSelected">
            <draggable
              :list="designer.fieldTree"
              v-bind="{
                group: 'dragGroup',
                ghostClass: 'ghost',
                animation: 300,
              }"
              handle=".drag-handler"
              :move="() => true"
              @update="onDragUpdate"
            >
              <transition-group name="fade" tag="div" class="form-unit-list">
                <template v-for="(unit, index) in designer.fieldTree">
                  <template v-if="typeof unit === 'string'">
                    <!-- {{ getUnitName(unit) }} -->
                    <!-- 输入字段单元 -->
                    <component
                      :is="getUnitName(unit)"
                      :key="unit"
                      :field-id="unit"
                      :designer="designer"
                      :parent-list="designer.fieldTree"
                      :index-of-parent-list="index"
                      :form-data="formModel"
                    />
                  </template>
                  <template v-else>
                    <!-- {{ getUnitName(unit.id) }} -->
                    <!-- 容器单元 -->
                    <component
                      :is="getUnitName(unit.id)"
                      :key="unit.id"
                      :field-id="unit.id"
                      :children="unit.children"
                      :designer="designer"
                      :parent-list="designer.fieldTree"
                      :index-of-parent-list="index"
                      :form-data="formModel"
                    />
                  </template>
                </template>
              </transition-group>
            </draggable>
          </el-row>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
/* eslint-disable vue/require-default-prop */
/* eslint-disable no-unused-vars */
/* eslint-disable eol-last */

import Draggable from "vuedraggable";
import "./con_unit/index";
import FieldComponents from "./field_unit/index";
// import TableUnit from "./field_unit/table_field_unit/table_unit.vue";

export default {
  components: {
    Draggable,
    ...FieldComponents,
    // table_unit: TableUnit,
  },
  props: {
    designer: Object,
    optionData: {
      type: Object,
      default: () => ({}),
    },
    globalDsv: {
      type: Object,
      default: () => ({}),
    },
  },
  provide() {
    return {
      globalModel: this,
      fieldLib: this.fieldLib,
      fieldUnit: (id) => this.fieldLib[id],
    };
  },
  data() {
    return {
      formModel: {},
      unitRefList: {},
      scrollerHeight: "auto",
      labelPosition: "left",
    };
  },
  computed: {
    formConfig: {
      cache: false,
      get() {
        return this.designer.formConfig;
      },
    },
    customClass() {
      return this.designer.formConfig.customClass || "";
    },
    fieldLib: {
      get() {
        return this.designer.fieldLib;
      },
    },
    fieldTree() {
      return this.designer.fieldTree;
    },
    layoutType() {
      return this.designer.getLayoutType();
    },
    size() {
      if (!!this.designer.formConfig && !!this.designer.formConfig.size) {
        return this.designer.formConfig.size;
      }
      return "medium";
    },
  },
  watch: {
    fieldLib: {
      handler(n) {
        // console.log("fieldLib change in unit_form", n);
        // console.log(JSON.stringify(n));
        this.initFormModelDefault();
      },
      deep: true,
    },
    fieldTree: {
      handler(n) {
        // console.log("fieldTree change in unit_form", n);
        // console.log(JSON.stringify(n));
        this.initFormModelDefault();
      },
    },
    // layoutType: {
    //   handler(n) {
    //     if (!n) return;
    //     const padW = n ? 10 : 20;
    //     console.log(1);
    //     this.scrollerHeight =
    //       document.querySelector(".unit-form-container").clientHeight -
    //       padW +
    //       "px";
    //   },
    //   immediate: true,
    // },
  },
  created() {
    // this.designer.initDesigner(!!this.getDesignerConfig().resetFormJson);
    // this.designer.loadPresetCssCode(this.getDesignerConfig().presetCssCode);
  },
  async mounted() {
    await this.$nextTick();
    this.$watch(
      "layoutType",
      (n) => {
        if (!n) return;
        const padW = n === "PC" ? 10 : 20;
        // console.log(1);
        this.scrollerHeight =
          document.querySelector(".unit-form-container").clientHeight -
          padW +
          "px";
      },
      { immediate: true }
    );
  },
  methods: {
    // 渲染/创建新字段时，$set到监听中
    initFormModelDefault() {
      const obj = {};
      const run = (arr) => {
        arr.forEach((i) => {
          const id = typeof i === "string" ? i : i.id;
          if (this.fieldLib[id].group === "field") {
            let newValue = this.fieldLib[i].options.defaultValue || null;
            if (this.fieldLib[id].type === "table") {
              const field = this.fieldLib[i];
              if (field.options.defaultRowValue) {
                // console.log("table rowValue");
                newValue = JSON.parse(field.options.defaultRowValue);
              } else {
                // console.log("table colValue", field.options.tableCols);
                const row = {};
                field.options.tableCols.forEach((o) => {
                  row[o] = this.fieldLib[o].options.defaultValue;
                });
                newValue = [row];
              }
              // console.log("setDefaultValue", newValue);
            }
            //  else if (this.fieldLib[id].type === "checkbox") {
            //   newValue = this.fieldLib[id].options.defaultValue || [];
            //   // if (!this.fieldLib[id].options.defaultValue)
            // }
            obj[id] = newValue;
          } else if (this.fieldLib[id].group === "container") {
            if (i.children.length !== 0) run(i.children);
          }
        });
      };
      run(this.fieldTree);
      // console.log("formModel", obj);
      this.$set(this, "formModel", obj);
    },
    clearSelected() {
      // console.log("clearSelected");
      this.designer.setSelected();
    },
    getUnitName(unit) {
      // console.log("getUnitName", this.fieldLib[unit]);
      return this.fieldLib[unit].type + "_unit";
    },
    onDragUpdate() {
      /* 在VueDraggable内拖拽组件发生位置变化时会触发update，未发生组件位置变化不会触发！！ */
      this.designer.emitHistoryChange();
    },
  },
};
</script>

<style lang="scss" scoped>
.container-scroll-bar {
  // height: calc(100vh - 42px);
  position: relative;
  overflow: hidden;
  overflow-y: auto;
  height: 100%;
  &::-webkit-scrollbar {
    display: none;
  }
}
// ::v-deep .container-scroll-bar {
//   .el-scrollbar__wrap,
//   .el-scrollbar__view {
//     overflow-x: hidden;
//   }
//   ::-webkit-scrollbar {
//     display: none;
//   }
// }

.unit-form-container {
  padding: 10px;

  background: #f1f2f3;
  overflow: hidden;
  height: 100%;

  &.PC-layout {
    padding-bottom: 0;
    .form-unit-list {
      min-height: calc(100vh - 42px - 40px - 49px);
    }
  }
  &.H5-layout {
    .el-form {
      margin: 0 auto;
      width: 350px;
      border-radius: 15px;
      //border-width: 10px;
      box-shadow: 0 0 1px 10px #495060;
      .form-unit-list {
        min-height: calc(100vh - 42px - 40px - 60px);
        overflow: hidden;
      }
    }
  }

  .el-form.full-height-width {
    overflow: hidden;
    // height: 100%;
    // padding: 3px;
    background: #ffffff;

    .no-unit-hint {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      font-size: 18px;
      color: #999999;
    }

    .form-unit-list {
      // min-height: calc(100vh - 42px - 40px - 61px);
      // min-height: 100%;
      padding: 6px;
    }
  }
}
.form-scrollbar {
  overflow: hidden;
  overflow-y: auto;
  &::-webkit-scrollbar {
    display: none;
  }
}

.grid-cell {
  min-height: 30px;
  border-right: 1px dotted #cccccc;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
::v-deep {
  .el-form.unit-form .el-row {
    padding: 2px;
    border: 1px dashed rgba(170, 170, 170, 0.75);
  }
}
</style>
